import { getUploadConfig } from "@/api/common"
export default async function upload(filePath, directory = 'uploadDynamic', accept) {
  uni.showLoading({
    title: '上传中...'
  });
  // if (accept === 'video') {
  //   filePath =  await videoCompress(filePath)
  // }
  return new Promise(async resolve => {
    const { code, data: { policy, url, accessId: OSSAccessKeyId, signature } } = await getUploadConfig('xiaochengxu/')
    // https://oss-cn-beijing.aliyuncs.com/zsjl
    let newFileName = fileName(directory, filePath)
    wx.uploadFile({
      url,
      filePath: filePath,
      name: 'file', // 必须填file。
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        name: newFileName,
        key: 'xiaochengxu/' + newFileName,
        policy,
        OSSAccessKeyId,
        success_action_status: '200',
        signature,
      },
      success: res => {
        if (res.statusCode === 200) {
          uni.hideLoading()
          console.log('上传成功', url + 'xiaochengxu/' + newFileName);
          resolve(url + 'xiaochengxu/' + newFileName)
        }
      },
      fail: err => {
        uni.hideLoading()
        console.log(err, 'err');
      }
    });
  })
}
let fileName = (directory, filePath, hashLength = 24) => {
  const suffix = filePath.substring(
    filePath.lastIndexOf('.') + 1
  )
  // 防止文件名冲突
  const random = Array.from(Array(Number(hashLength)), () => Math.floor(Math.random() * 36).toString(36)).join('')
  return `${directory}/${suffix}/${random}.${suffix}`
}
// 视频压缩 微信开发者工具需要ffepeg 在D盘
function videoCompress(tempFilePath) {
  return new Promise((resolve, reject) => {
    uni.compressVideo({
      src: tempFilePath,
      quality: 'medium', //'low':低，'medium':中，'high':高  
      success: res => {
        console.log(res)
        resolve(res.tempFilePath)
      },
      fail: err => {
        console.log(err)
        resolve(tempFilePath)
        uni.showToast({
          title: '视频压缩失败',
          icon: 'none'
        }, 2000)
      }
    })
  })
}